<template>
  <div class="search">
    <van-nav-bar
      title="搜索中心"
      left-arrow
      @click-left="$router.back()"
    ></van-nav-bar>

    <!-- 搜索框 -->
    <van-search
      v-model.trim="value"
      show-action
      shape="round"
      action-text="搜索"
      placeholder="请输入搜索关键词"
      @input="onInput"
    >
      <template #action>
        <div @click="Search(value)">搜索</div>
      </template>
    </van-search>

    <!-- 推荐 -->
    <van-cell-group v-if="value">
      <van-cell
        icon="search"
        v-for="(item, index) in sugList"
        :key="index"
        @click="onSearch(item)"
      >
        <span v-html="highLight(item, value)"></span>
      </van-cell>
    </van-cell-group>

    <!-- 历史记录 -->
    <van-cell-group v-else>
      <van-cell title="历史记录"></van-cell>
      <van-cell
        :title="item"
        v-for="(item, index) in history"
        :key="index"
        @click="onSearch(item)"
      >
        <van-icon name="close" @click.stop="del(item)" />
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
import { getSuggest } from '@/api/search'
import {
  setStroageSearchHistory,
  getStroageSearchHistory
} from '@/utils/stroage'
export default {
  name: 'Search',
  data() {
    return {
      value: '',
      // 推荐列表
      sugList: [],
      // 搜索关键字的数组 （数组的为测试数据）
      history: getStroageSearchHistory()
    }
  },
  methods: {
    highLight(str, keyword) {
      const reg = new RegExp(keyword, 'gi')
      return str.replace(
        reg,
        (item) => `<span style="color:red">${item}</span>`
      )
    },
    Search(value) {
      if (!this.value) return this.$toast('请输入关键字')
      this.history = this.history.filter((item) => item !== this.value)
      if (this.value !== '') this.history.unshift(this.value)

      // 存到本地
      setStroageSearchHistory(this.history)

      // 跳转路由
      this.$router.push({
        path: '/search/result',
        query: {
          keyword: value
        }
      })
    },
    onInput() {
      console.log(this)
      clearTimeout(this.timerId)
      this.timerId = setTimeout(async () => {
        if (!this.value) return this.$toast('请输入关键字')
        const res = await getSuggest(this.value)
        if (res.data.options[0] === null) {
          // 这次没有数据
          return (this.sugList = [])
        }

        this.sugList = res.data.options
      }, 500)
    },
    onSearch(item) {
      // 添加历史记录
      // 先筛选出向历史记录里已有的
      this.history = this.history.filter((item) => item !== this.value)
      if (this.value !== '') this.history.unshift(this.value)

      // 存到本地
      setStroageSearchHistory(this.history)

      // 跳转路由
      this.$router.push({
        path: '/search/result',
        query: {
          keyword: item
        }
      })
    },
    del(item) {
      // 删除历史记录
      this.history = this.history.filter((v) => v !== item)
      // 存到本地
      setStroageSearchHistory(this.history)
    }
  }
}
</script>

<style></style>
